package com.lintf.devdemo.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.lintf.devdemo.dao.ISysFileInfoMapper;
import com.lintf.devdemo.entity.po.ISysFileInfo;
import com.lintf.devdemo.service.ISysFileInfoService;
import com.lintf.devdemo.utils.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.time.LocalDateTime;
import java.util.*;
import java.util.List;

/**
 * @ system:Window
 * @ author:lin tingfeng
 * @ data:2022/10/19-15:10
 * @ package_name:com.lintf.devdemo.service.Impl
 * @ project_name:DevDemo
 * @ desc:系统文件处理逻辑实现
 */
@Service
@Transactional
public class ISysFileInfoServiceImpl implements ISysFileInfoService {

    @Value("${file.upload.path}")
    private String fileUploadPath;

    @Value("${base-url}")
    private String BASE_URL;

    @Value("${hyl.web.url:#{null}}")
    private String HYL_WEB_URL = "";

    @Autowired
    private ISysFileInfoMapper iSysFileInfoMapper;


    /**
     * 上传压缩文件
     * @param files
     * @param relatedPK
     * @param relatedTable
     * @param refType
     * @param howBigNeedCompress
     * @return
     * @throws Exception
     */
    @Override
    public List<ISysFileInfo> uploadCompress(MultipartHttpServletRequest files, String relatedPK, String relatedTable, String refType, int howBigNeedCompress) throws Exception {
        Date uploadTime = new Date();
        if (!this.fileUploadPath.endsWith("/")) {
            this.fileUploadPath = this.fileUploadPath + "/";
        }
        String uploaderId = UUID.randomUUID().toString().replaceAll("-","");
        List<ISysFileInfo> fileInfos = this.upload(this.fileUploadPath, files, "admin",uploaderId, uploadTime, relatedPK, relatedTable, refType);
        if (null != fileInfos && fileInfos.size() > 0) {
            ISysFileInfo fileInfo = (ISysFileInfo) fileInfos.get(0);
            File inFile = new File(fileInfo.getFileLocation());
            if (inFile.length() / 1024L > (long) howBigNeedCompress && (fileInfo.getFileType().equals("image/jpeg") || fileInfo.getFileType().equals("image/jpg") || fileInfo.getFileType().equals("image/png"))) {
                FileUtil.compress(fileInfo.getFileLocation());
            }
        }

        String url = this.BASE_URL;
        if (StringUtils.isNotEmpty(this.HYL_WEB_URL)) {
            url = this.HYL_WEB_URL;
        }

        Iterator var11 = fileInfos.iterator();

        while (var11.hasNext()) {
            ISysFileInfo fileInfo = (ISysFileInfo) var11.next();
            String id = fileInfo.getId();
                fileInfo.setUrl(url + "/sysFileInfo/showImgStream?id=" + id);
        }

        fileInfos.forEach((f) -> {
            f.setCanDownLoad(1);
            System.err.println(f);
        });
        return fileInfos;
    }

    public List<ISysFileInfo> upload(String rootPath, MultipartHttpServletRequest files, String uploader, String uploaderId, Date uploadTime, String refId, String refTable, String refType) {
        ArrayList fileInfoList = new ArrayList();

        Iterator iter;
        try {
            String folderPath = FileUtil.getFolderPath(rootPath, uploadTime);
            iter = files.getFileNames();

            while (iter.hasNext()) {
                String fileName = (String) iter.next();
                MultipartFile file = files.getFile(fileName);
                ISysFileInfo fileInfo = FileUtil.ajaxUplod(file, folderPath);
                fileInfo.setRefId(refId);
                fileInfo.setRefTable(refTable);
                fileInfo.setRefType(refType);
                fileInfo.setUploadPerson(uploader);
                fileInfo.setUploadPersonId(uploaderId);
                fileInfo.setUploadTime(LocalDateTime.now());
                fileInfoList.add(fileInfo);
            }

            this.saveUploadResult(fileInfoList);
        } catch (Exception var15) {
            System.err.printf("上传文件失败", var15);
            iter = fileInfoList.iterator();
            while (iter.hasNext()) {
                ISysFileInfo sysFileInfo = (ISysFileInfo) iter.next();
                File file = new File(sysFileInfo.getFileLocation());
                if (file.exists()) {
                    file.delete();
                }
            }
        }

        return fileInfoList;
    }

    public void saveUploadResult(List<ISysFileInfo> fileInfos) {
        fileInfos.forEach((e) -> {
            if (StringUtils.isBlank(e.getId())) {
                e.setId(UUID.randomUUID().toString().replaceAll("-",""));
            }
        });
        fileInfos.forEach((fileInfo) -> {
            iSysFileInfoMapper.insert(fileInfo);
        });
    }

    /**
     * 上传文件列表
     * @return
     */
    @Override
    public List<ISysFileInfo> uploadFileList() {
        return iSysFileInfoMapper.selectList(null);
    }
}
